package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeParseException;
import java.util.Arrays;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.alibaba.fastjson.JSON;
import com.zzyl.common.utils.CodeGenerator;
import org.springframework.transaction.annotation.Transactional;


/**
 * 入住Service业务层处理
 * 
 * @author alexis
 * @date 2025-05-26
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
   private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private ContractMapper contractMapper;
    /**
     * 查询入住
     *
     * @param id 入住主键
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }

    /**@param checkInApplyDto
     * */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto checkInApplyDto) {
        // 判断老人是否已经入住
        // 通过身份证号查询老人
        LambdaQueryWrapper<Elder> elderQueryWrapper = new LambdaQueryWrapper<Elder>();
        elderQueryWrapper.eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo());
        elderQueryWrapper.eq(Elder::getStatus, 1);
        Elder elder = elderMapper.selectOne(elderQueryWrapper);
        if (ObjectUtils.isNotEmpty(elder)) {
            throw new BaseException("老人已入住");
        }

        //更新床位状态表示已入住
        //根据入住配置中的床位ID查询床位信息，并进行校验

        // 更新床位的状态  已入住
        Bed bed = bedMapper.selectById(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        // 保存或更新老人数据
        elder = insertOrUpdate(bed, checkInApplyDto.getCheckInElderDto());

        //生成合同编号
        //生成合同编号
        String contractNo = "HT" + CodeGenerator.generateContractNumber();

        //新增签约合同办理业务
        insertContract(contractNo, elder, checkInApplyDto);
        //新增入住业务
        CheckIn checkIn = insertCheckIn(elder, checkInApplyDto);
        //新增入住配置信息1
        insertcheckInConfig(checkIn.getId(), checkInApplyDto);

    }

    //新增入住信息
    /**
     * @param checkInApplyDto
     */

    private void insertcheckInConfig(Long checkInId, CheckInApplyDto checkInApplyDto) {
        CheckInconfig checkInconfig = new CheckInconfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkInconfig);
        checkInconfig.setCheckInId(checkInId);
        checkInConfigMapper.insert(checkInconfig);
    }
/**新增入住信息
 * @param checkInApplyDto
 * @param elder
 *
 * */
private CheckIn insertCheckIn(Elder elder,CheckInApplyDto checkInApplyDto){
    //创建新的入住记录对象
    CheckIn checkIn = new CheckIn();
    // 设置老人ID
    checkIn.setElderId(elder.getId());
    // 设置老人身份证号
    checkIn.setElderName(elder.getName());
    checkIn.setIdCardNo(elder.getIdCardNo());

    // 设置护理等级名称（从入住配置DTO获取）
    checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());


    // 设置入住开始日期（从入住配置DTO获取）
    checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getEndDate());

    // 设置入住结束日期（从入住配置DTO获取）
    checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());

    // 设置床位号（从老人实体获取）
    checkIn.setBedNumber(elder.getBedNumber());

    // 设置备注信息（将家属列表转为JSON字符串）
    checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));

    checkIn.setStatus(0);
    checkInMapper.insert(checkIn);
    return checkIn;
    // 设置入住状态（0表示初始状态）


    // 执行数据库插入操作

    // 返回新增的入住记录

}
/**@parm contractNo
 * @param elder
 * @param checkInApplyDto
 * */
private void insertContract(String contractNo, Elder elder, CheckInApplyDto checkInApplyDto) {
    Contract contract = new Contract();
    BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
  contract.setContractNumber(contractNo);
    contract.setElderId(elder.getId().intValue());
    contract.setElderName(elder.getName());

 LocalDateTime checkInStartTime = checkInApplyDto.getCheckInConfigDto().getStartDate();
    LocalDateTime checkInEndTime = checkInApplyDto.getCheckInConfigDto().getEndDate();
    Integer status = checkInStartTime.isBefore(LocalDateTime.now()) ? 0:1;
   contract.setStatus(status);
   contract.setEndDate(checkInEndTime);
   contract.setStartDate(checkInStartTime);
   contractMapper.insert(contract);

}
/**
 * 新增更新老人
 * @param bed
 * @param checkInElderDto
 * @return
 * */
private Elder insertOrUpdate(Bed bed, CheckInElderDto checkInElderDto){
    //准备老人数据
    Elder elder = new Elder();
    //属性拷贝
    BeanUtils.copyProperties(checkInElderDto , elder);
    elder.setBedNumber(bed.getBedNumber());
    elder.setBedId(bed.getId());
    elder.setStatus(1);
    //查询老人信息身份证状态不为1
    LambdaQueryWrapper<Elder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
    lambdaQueryWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo()).ne(Elder::getStatus, 1);
    Elder elderDb = elderMapper.selectOne(lambdaQueryWrapper);
    if(ObjectUtils.isNotEmpty(elderDb)){ // ← 判断是否存在
        // 修改
        elderMapper.updateById(elder);
    }else{
        // 新增
        elderMapper.insert(elder);
    }

return elder;
}

    @Override
    public CheckInDetailVo selectDetail(Long id) {

    //获取入住配置xx
        CheckIn checkIn = checkInMapper.selectById(id);
        if(checkIn == null){
            throw new BaseException("入住信息不存在");
        }
        //构建返回对象
        CheckInDetailVo detailVo = new CheckInDetailVo();

    //获取老人信息
        CheckInElderVo checkInElderVo= new CheckInElderVo();
        Elder elder = elderMapper.selectById(checkIn.getElderId());
        if(elder != null){
            BeanUtils.copyProperties(elder,checkInElderVo);
            if(StringUtils.isNoneBlank(elder.getImage())){
                try{
                    LocalDate bitrate = LocalDate.parse(elder.getBirthday());
                    checkInElderVo.setAge(LocalDate.now().getYear() - bitrate.getYear());
                }catch (DateTimeParseException e){
                    System.out.println("日期转换异常");
                }
            }
            detailVo.setCheckInElderVo(checkInElderVo);
        }
        BeanUtils.copyProperties(elder,checkInElderVo);
        detailVo.setCheckInElderVo(checkInElderVo);
        //查询家属信息
        List<ElderFamilyVo> familyList = JSON.parseArray(checkIn.getRemark(),ElderFamilyVo.class);
        detailVo.setElderFamilyVoList(familyList);

        // 获取入住配置信息
        LambdaQueryWrapper<CheckInconfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CheckInconfig::getCheckInId, id);
        CheckInconfig checkInConfig = checkInConfigMapper.selectOne(queryWrapper);

        CheckInConfigVo configVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig,  configVo);
        configVo.setEndDate(checkIn.getEndDate());
        configVo.setStartDate(checkIn.getStartDate());
        elder.setBedNumber(checkIn.getBedNumber());
        configVo.setBedNumber(elder.getBedNumber());
        detailVo.setCheckInConfigVo(configVo);

        //查询合同信息
        LambdaQueryWrapper<Contract> contractWrapper = new LambdaQueryWrapper<>();
        contractWrapper.eq(Contract::getElderId, elder.getId().intValue());
        Contract contract = contractMapper.selectOne(contractWrapper);
        detailVo.setContract(contract);
        return detailVo;

    }
}






